import json
import os
import cv2
from cv2.wechat_qrcode import WeChatQRCode
import sys
import urllib.request
import numpy as np


def image_change(img, path, height, width, min_px):
    if height < min_px or width < min_px:
        if height < min_px:
            rate = min_px / height
            height = min_px
            width = int(width * rate)
        if width < min_px:
            rate = min_px / width
            width = min_px
            height = int(height * rate)
        cacheImg = cv2.resize(img, (width, height), interpolation=cv2.INTER_CUBIC)
        cv2.imwrite(path, cacheImg)
    else:
        cv2.imwrite(path, img)

    images = cv2.imread(path)
    detect_obj = WeChatQRCode()
    res, _ = detect_obj.detectAndDecode(images)
    if len(res) == 0:
        if min_px > 2000:
            print('end')
            return 0

        res = image_change(img, path, height, width, min_px + 100)

    return res


if __name__ == "__main__":
    arr = {
        "code": 0,
    }

    if sys.argv[1] is None or sys.argv[1] == '':
        print(json.dumps(arr))
        sys.exit()

    try:
        imgURl = sys.argv[1]
        # 获取文件名
        path = imgURl.split('/')[-1]
        resp = urllib.request.urlopen(imgURl)
        image = np.asarray(bytearray(resp.read()), dtype="uint8")

        img = cv2.imdecode(image, cv2.IMREAD_GRAYSCALE)  # 灰度
        # 尺寸小于 放大图片
        height, width = img.shape[:2]
        res = image_change(img, path, height, width, 700)
        # 删除文件
        if os.path.exists(path):
            os.remove(path)
        if res == 0:
            print(json.dumps(arr))
            sys.exit()
        arr["code"] = 1
        arr["url"] = res[0]
        print(json.dumps(arr))
    except Exception as e:
        print(e)
        sys.exit()
